const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const modelName = 'Comment';
const CommentState = ['未审核', '审核通过', '审核不通过'];

const CommentSchema = new Schema({
  from: { type: String, default: '历史数据' },
  refNewsId: { type: Schema.Types.ObjectId },
  data: String,
  state: {
    type: String,
    enum: CommentState,
    default: CommentState[0],
  },
}, {
  timestamps: { createdAt: 'createdAt', updatedAt: 'updatedAt' }
});

CommentSchema.statics.createComment = async function(comment) {
  return await new Comment(comment).save();
}

CommentSchema.statics.obtainComment = async function(_id) {
  return await (await Comment.findById(_id));
}

CommentSchema.statics.obtainAllComment = async function(_id, specifiedState) {
  const q = null == specifiedState ? {} : { state: specifiedState };
  return await Comment.find(q);
}

CommentSchema.statics.verifyComment = async function(_id, state) {
  const commentDoc = await Comment.findById(_id).where({
    state: CommentState[0],
  });
  commentDoc.state = state;
  return await commentDoc.save();
}

CommentSchema.options.toJSON = {
  transform: function(doc, ret, options) {
      delete ret.__v;
      return ret;
  },
};

const Comment = mongoose.model(modelName, CommentSchema);

exports.model = Comment;
exports.CommentState = CommentState;